<html>
    <head>
        <title>TrackIR in WebGL</title>
        <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
        <script type="text/javascript" src="web_js/glMatrix-0.9.5.min.js"></script>
        <script type="text/javascript" src="web_js/trackirController.js"></script>
        <script type="text/javascript" src="web_js/testScene.js"></script>
    </head>
    <body onload="webGLStart();">
    <div id="outputTest" style="position:absolute; top:20px; left:20px"></div>

<script id="shader-fs" type="x-shader/x-fragment">
    #ifdef GL_ES
    precision highp float;
    #endif

    varying vec4 vColor;

    void main(void) {
        //gl_FragColor = vec4(1,0,0,1);
        gl_FragColor = vColor;
    }
</script>

<script id="shader-vs" type="x-shader/x-vertex">
    attribute vec3 aVertexPosition;
    attribute vec4 aVertexColor;

    uniform mat4 uMVMatrix;
    uniform mat4 uPMatrix;

    varying vec4 vColor;

    void main(void) {
        gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
        vColor = aVertexColor;
    }
</script>

<script type="text/javascript">
    var trackIR = new trackIRController();

    var gl;
    function initGL(canvas) {
        try {
            gl = canvas.getContext("experimental-webgl");
            gl.viewportWidth = canvas.width;
            gl.viewportHeight = canvas.height;
        } catch(e) {
        }
        if (!gl) {
            alert("Could not initialise WebGL, sorry :-(");
        }
    }

    function getShader(gl, id) {
        var shaderScript = document.getElementById(id);
        if (!shaderScript) {
            return null;
        }
        var str = "";
        var k = shaderScript.firstChild;
        while (k) {
            if (k.nodeType == 3) {
                str += k.textContent;
            }
            k = k.nextSibling;
        }

        var shader;
        if (shaderScript.type == "x-shader/x-fragment") {
            shader = gl.createShader(gl.FRAGMENT_SHADER);
        } else if (shaderScript.type == "x-shader/x-vertex") {
            shader = gl.createShader(gl.VERTEX_SHADER);
        } else {
            return null;
        }

        gl.shaderSource(shader, str);
        gl.compileShader(shader);

        if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
            alert(gl.getShaderInfoLog(shader));
            return null;
        }

        return shader;
    }

    var shaderProgram;
    function initShaders() {
        var fragmentShader = getShader(gl, "shader-fs");
        var vertexShader = getShader(gl, "shader-vs");

        shaderProgram = gl.createProgram();
        gl.attachShader(shaderProgram, vertexShader);
        gl.attachShader(shaderProgram, fragmentShader);
        gl.linkProgram(shaderProgram);

        if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
            alert("Could not initialise shaders");
        }

        gl.useProgram(shaderProgram);

        shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition");
        gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);

        shaderProgram.vertexColorAttribute = gl.getAttribLocation(shaderProgram, "aVertexColor");
        gl.enableVertexAttribArray(shaderProgram.vertexColorAttribute);

        shaderProgram.pMatrixUniform = gl.getUniformLocation(shaderProgram, "uPMatrix");
        shaderProgram.mvMatrixUniform = gl.getUniformLocation(shaderProgram, "uMVMatrix");
    }


    var mvMatrix = mat4.create();
    var mvMatrixStack = [];
    var pMatrix = mat4.create();

    function mvPushMatrix() {
        var copy = mat4.create();
        mat4.set(mvMatrix, copy);
        mvMatrixStack.push(copy);
    }

    function mvPopMatrix() {
        if (mvMatrixStack.length == 0) {
            throw "Invalid popMatrix!";
        }
        mvMatrix = mvMatrixStack.pop();
    }


    function setMatrixUniforms() {
        gl.uniformMatrix4fv(shaderProgram.pMatrixUniform, false, pMatrix);
        gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mvMatrix);
    }


    function degToRad(degrees) {
        return degrees * Math.PI / 180;
    }

    var testSceneBuffer;
    var trackIRMatrix = mat4.create();
    mat4.identity(trackIRMatrix);
    var d = document.getElementById("outputTest");

    function initBuffers() {
        testSceneData = initTestSceneBuffers();

        testSceneBuffer = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER, testSceneBuffer);
        gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(testSceneData), gl.STATIC_DRAW);
        testSceneBuffer.numItems = testSceneData.length / 7;
        gl.bindBuffer(gl.ARRAY_BUFFER, null);
    }

    function printData(matData) {
        var tmpData = "";
        tmpData += matData[0] + ", " + matData[1] + ", " + matData[2] + ", " + matData[3] + "<br>\n";
        tmpData += matData[4] + ", " + matData[5] + ", " + matData[6] + ", " + matData[7] + "<br>\n";
        tmpData += matData[8] + ", " + matData[9] + ", " + matData[10] + ", " + matData[11] + "<br>\n";
        tmpData += matData[12] + ", " + matData[13] + ", " + matData[14] + ", " + matData[15] + "<br>\n";
        d.innerHTML = tmpData;
    }

    function drawScene() {
        if(keyPressed(67)) { trackIR.tirRecenter(); } // c key pressed

        tirMatrix = trackIR.tirGetMatrix();
        tirMatrix[12] /= 50 * -1;
        tirMatrix[13] /= 50 * -1;
        tirMatrix[14] /= 50 * -1;
        printData(tirMatrix);

        if(tirMatrix[0] >= 1 && tirMatrix[1] == 0 && tirMatrix[2] == 0 && tirMatrix[3] == 0) {
        } else {
            trackIRMatrix = tirMatrix;
        }

        gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight);
        gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

        mat4.perspective(45, gl.viewportWidth / gl.viewportHeight, 0.1, 1000.0, pMatrix);
        mat4.identity(mvMatrix);

        mat4.translate(mvMatrix, [0.0, -10.0, 0.0]);
        mat4.multiply(mvMatrix, trackIRMatrix);

        mvPushMatrix();
        gl.bindBuffer(gl.ARRAY_BUFFER, testSceneBuffer);
        gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, 3, gl.FLOAT, false, 28, 0);
        gl.vertexAttribPointer(shaderProgram.vertexColorAttribute, 4, gl.FLOAT, false, 28, 12);
        setMatrixUniforms();
        gl.drawArrays(gl.TRIANGLES, 0, testSceneBuffer.numItems);
        mvPopMatrix();

        requestAnimFrame(drawScene);
    }

    function webGLStart() {
        var canvas = document.getElementById("TrackIRCanvas");
        initGL(canvas);
        initShaders()
        initBuffers();

        gl.clearColor(0.0, 0.0, 0.0, 1.0);
        gl.clearDepth(1.0);

        gl.enable(gl.DEPTH_TEST);
        gl.depthFunc(gl.LEQUAL);

        drawScene();
    }

    window.requestAnimFrame = (function() {
      return window.requestAnimationFrame ||
             window.webkitRequestAnimationFrame ||
             window.mozRequestAnimationFrame ||
             window.oRequestAnimationFrame ||
             window.msRequestAnimationFrame ||
             function(/* function FrameRequestCallback */ callback, /* DOMElement Element */ element) {
               window.setTimeout(callback, 1000/60);
             };
    })();

</script>
  <canvas id="TrackIRCanvas" style="border: none;" width="1024" height="768"></canvas>

</body>


<script language="JavaScript">

    //----
    // Key press detection
    //----
    var eventList = new function() {
        this.addEvent = function(eventType, eventElement, eventFunction) {
            if(eventElement.addEventListener) {
                eventElement.addEventListener(eventType, eventFunction, false);
            } else if(eventElement.attachEvent) {
                eventType = ((eventType == "DOMMouseScroll") ? "mousewheel" : eventType);
                eventElement.attachEvent('on' + eventType, eventFunction);
            }
        }
        this.removeEvent = function(eventType, eventElement, eventFunction) {
            if(eventElement.removeEventListener) {
                eventElement.removeEventListener(eventType, eventFunction, false);
            } else if(eventElement.removeEvent) {
                eventType = ((eventType == "DOMMouseScroll") ? "mousewheel" : eventType);
                eventElement.removeEvent('on' + eventType, eventFunction);
            }
        }
    }
    var keyList = "-";
    function keyDown(e) { if(keyList.indexOf("-" + e.keyCode + "-") == -1) { keyList += e.keyCode + "-"; } }
    function keyUp(e) { keyList = keyList.replace("-" + e.keyCode + "-", "-"); }
    function keyPressed(keyCode) {
        if(keyList.indexOf("-" + keyCode + "-") >= 0) {
            return true;
        } else {
            return false;
        }
    }
    eventList.addEvent('keydown', window, keyDown);
    eventList.addEvent('keyup', window, keyUp);

</script>
</html>

